package servlet;

import org.owasp.esapi.errors.EncodingException;
import utility.Utility;
import data.DownloadRecordData;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;

@WebServlet(name = "DownloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String table = request.getParameter("table");
        String id = request.getParameter("id");
        String column = request.getParameter("column");
        String tableName = Utility.getTableName(Integer.parseInt(table));
        DownloadRecordData downloadRecordData = new DownloadRecordData(id, column);
        Blob resultBlob = downloadRecordData.downloadData(tableName);
        try {
            tableName = downloadRecordData.sanitize(tableName);
            column = downloadRecordData.sanitize(column);
            id = downloadRecordData.sanitize(id);
        } catch (EncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition",
                "attachment;filename=" + tableName + "_" + column + "_" + id);
        response.setContentType("multipart/form-data");
        try {
            InputStream inputStream = resultBlob.getBinaryStream();
            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            inputStream.close();
            outputStream.close();
            outputStream.flush();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        doPost(request, response);
    }
}
